package org.example.config.autowire.fiegn;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.ClassUtils;

import java.util.Map;
import java.util.Set;


public class EnableFeignAutoConfigRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        // scanner.setResourceLoader(this.resourceLoader);
        scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));

        String defaultPackage = ClassUtils.getPackageName(importingClassMetadata.getClassName());

        Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(defaultPackage);

        for (BeanDefinition bd : beanDefinitions) {
            AnnotatedBeanDefinition abd = (AnnotatedBeanDefinition) bd;
            AnnotationMetadata am = abd.getMetadata();
            Map<String, Object> attributes = am.getAnnotationAttributes(FeignClient.class.getName());
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FeignClientProxy.class)
                    .addPropertyValue("url", attributes.get("url"))
                    .addPropertyValue("name", attributes.get("name"));
            registry.registerBeanDefinition(ClassUtils.getShortName(am.getClassName()), builder.getBeanDefinition());
        }
    }
}
